<template>
  <div>
    <!-- 查看详情弹框 -->
    <el-dialog
      title="图片配置"
      :visible.sync="imgShow"
      width="70%"
      :before-close="handleCloses"
      append-to-body
      :close-on-click-modal="false"
    >
      <div v-loading="listLoading">
        <p class="shopList">配置预览图</p>
        <el-upload
          :action="httpurl + '/api/fileUpload'"
          list-type="picture-card"
          :file-list="imgData"
          :limit="3"
          name="file"
          accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
          :on-error="handleFail"
          :before-upload="beforeUpload"
          :on-success="handleSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <div v-if="imgData.length > 0">
          <div v-for="(item, i) in imgData" :key="i + 'a'">
            <span class="imgSpan" @click="datasss(i)">
              <el-radio v-model="radio" :label="i">设置为封面</el-radio>
            </span>
          </div>
        </div>

        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
        <div style="clear:both"></div>
        <p class="f12">
          要求：345：140尺寸，不超过1M，请至少上传1张图片，最多可配置3张标题预览图
        </p>

        <p class="shopList">配置活动图背景</p>
        <el-upload
          :action="httpurl + '/api/fileUpload'"
          name="file"
          list-type="picture-card"
          :file-list="imgData2"
          :limit="3"
          accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
          :before-upload="beforeUpload1"
          :on-error="handleFail"
          :on-success="handleSuccess2"
          :on-preview="handlePictureCardPreview2"
          :on-remove="handleRemove2"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible2" append-to-body>
          <img width="100%" :src="dialogImageUrl2" alt="" />
        </el-dialog>
        <p class="f12">
          要求：不超过1M，请至少上传1张图片，最多可配置3张标题预览图
        </p>

        <div class="primary">
          <el-button type="primary" @click="fromData" class="primaryIpt"
            >完成</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import bus from "../../assets/js/bus";
import https from "../../plugins/https.js";
export default {
  props: {
    imgShow: {
      type: Boolean,
      default() {
        return false;
      }
    },
    imgDataBounced: {
      type: Object
    }
  },
  data() {
    return {
      imgData: [],
      imgData2: [],
      listLoading: false,
      dialogImageUrl: "",
      dialogVisible: false,
      dialogImageUrl2: "",
      dialogVisible2: false,
      radio: "",
      file: "",
      file2: "",
      coverPhotos: [],
      bgPhotos: [],
      httpurl: this.GLOBAL.httpurl
    };
  },
  watch: {
    imgShow(n) {
      if (n === true) {
        this.resetFields();
      }
    }
  },
  mounted() {
    console.log(555, this.eventShow);
  },
  methods: {
    handleFail() {
      layer.open({
        content: "图片上传失败，请重新上传",
        skin: "msg",
        time: 1, //1秒后自动关闭
      });
    },
    resetFields() {
      this.imgData = [];
      this.imgData2 = [];
      this.radio = "";
      this.file = "";
      this.file2 = "";
      this.coverPhotos = [];
      this.bgPhotos = [];
      let coverPhotos
      // 回显
      console.log(this.imgDataBounced.coverPhotos)
      this.imgDataBounced.coverPhotos=='undefined'?'': coverPhotos = JSON.parse(
        JSON.stringify(this.imgDataBounced.coverPhotos)
      );
      // let coverPhotos = JSON.parse(
      //   JSON.stringify(this.imgDataBounced.coverPhotos)
      // );
      let bgPhotos = JSON.parse(JSON.stringify(this.imgDataBounced.bgPhotos));
      if (coverPhotos.length > 0) {
        this.imgData = coverPhotos.map((ele, i) => {
          // 最后将数据给fileLis
          let item = {};
          item = ele;
          item.url = ele.filePath;
          item.id = ele.id;
          item.filePath = ele.filePath;
          ele.status == "1" && this.datasss(i);
          return item;
        });
      }
      if (bgPhotos.length > 0) {
        this.imgData2 = bgPhotos.map(ele => {
          // 最后将数据给fileLis
          let item = {};
          item = ele;
          item.url = ele.filePath;
          item.filePath = ele.filePath;
          item.id = ele.id;
          return item;
        });
      }
    },
    datasss(i) {
      this.radio = i;
    },
    handleCloses(done) {
      this.imgData = [];
      this.imgData2 = [];
      this.radio = "";
      this.file = "";
      this.file2 = "";
      this.coverPhotos = [];
      this.bgPhotos = [];
      bus.$emit("imgSuccess", { type: 2, show: false });
    },
    fromData() {
      if (this.imgData.length < 1)
        return this.$notify({
          title: "错误",
          message: "请上传预览图",
          type: "error"
        });
      if (this.imgData2.length < 1)
        return this.$notify({
          title: "错误",
          message: "请上传背景图",
          type: "error"
        });
      if (this.radio === "")
        return this.$notify({
          title: "错误",
          message: "请选择封面",
          type: "error"
        });

      for (let i = 0; i < this.imgData.length; i++) {
        let pl = {
          filePath: this.imgData[i].filePath,
          status: i == this.radio ? 1 : 0,
          id: this.imgData[i].id
        };
        this.coverPhotos.push(pl);
      }

      for (let i = 0; i < this.imgData2.length; i++) {
        let pl = {
          filePath: this.imgData2[i].filePath,
          status: 0,
          id: this.imgData2[i].id
        };
        this.bgPhotos.push(pl);
      }
      let pl = JSON.parse(JSON.stringify(this.imgDataBounced));
      pl.coverPhotos = this.coverPhotos;
      pl.bgPhotos = this.bgPhotos;
      this.listLoading = true;
      // return
      https.savePayActive(pl).then(res => {
        if (res.data.code !== "0000") {
          this.$notify({ title: "错误", message: res.data.msg, type: "error" });
          this.listLoading = false;
          return;
        }
        this.resetFields();
        this.$notify({ title: "成功", message: res.data.msg, type: "success" });
        this.listLoading = false;
        bus.$emit("imgSuccess", { type: 1, show: false });
      });
    },
    handleRemove(file, fileList) {
      console.log(this.imgData.length)
      if (this.imgData.length <= 1) {
        for (let i = 0; i < this.imgData.length; i++) {
          this.imgData[i].uid == file.uid && this.imgData.splice(i, 1);
          this.imgData[i].status == 1 && (this.radio = "");
        }
      }
    },
    beforeUpload(file) {
      let newName = file.name.substring(file.name.lastIndexOf("."));
      let islt1M = file.size / 1024 / 1024 < 1000;
      if (!islt1M) {
        this.$notify({
          title: "错误",
          message: "图片尺寸限制为345：140",
          type: "error"
        });
        return false;
      } else {
        const isSize = new Promise((resolve, reject) => {
          // const width = 345;
          // const height = 140;
          const _URL = window.URL || window.webkitURL;
          const img = new Image();
          img.onload = () => {
            let name =
              file.name.substring(0, file.name.lastIndexOf(".")) +
              "_" +
              img.width +
              "_" +
              img.height +
              newName;
            file = new File([file], name);

            const valid = this.$commit.ImageRestrictions(
              img.width,
              img.height,
              1
            );
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$notify({
              title: "错误",
              message: "图片尺寸限制为345：140，大小不可超过1M",
              type: "error"
            });
            return Promise.reject();
          }
        );
        return isSize;
      }
    },
    beforeUpload1(file) {
      let newName = file.name.substring(file.name.lastIndexOf("."));
      let islt1M = file.size / 1024 / 1024 < 1000;
      if (!islt1M) {
        this.$notify({
          title: "错误",
          message: "上传图片大小不能超过1M",
          type: "error"
        });
        return false;
      } else {
        const isSize = new Promise((resolve, reject) => {
          const width = 2000;
          const _URL = window.URL || window.webkitURL;
          const img = new Image();
          img.onload = () => {
            let name =
              file.name.substring(0, file.name.lastIndexOf(".")) +
              "_" +
              img.width +
              "_" +
              img.height +
              newName;
            file = new File([file], name);

            const valid = img.width < width;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$notify({ title: "错误", message: "图片过大", type: "error" });
            return Promise.reject();
          }
        );
        console.log(33333, file);
        return isSize;
      }
    },
    handleSuccess(res, file, fileList) {
      // let islt1M = file.size / 1024 / 1024 < 0.2
      // if (!islt1M) {
      //   this.$notify({title: "错误",message: '上传图片大小不能超过200kb',type: "error"});
      //   return false
      // }
      this.file = file.url;
      let pl = {
        status: "0",
        filePath: res.data.filePath,
        url: res.data.filePath
      };
      this.imgData.push(pl);
    },
    handleSuccess2(res, file, fileList) {
      // let islt1M = file.size / 1024 / 1024 < 0.2
      // if (!islt1M) {
      //   this.$notify({title: "错误",message: '上传图片大小不能超过200kb',type: "error"});
      //   return false
      // }
      this.file2 = file.url;
      let pl = {
        status: "0",
        filePath: res.data.filePath,
        url: res.data.filePath
      };
      this.imgData2.push(pl);
    },
    handlePictureCardPreview(file, fileList) {
      console.log(444, file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove2(file, fileList) {
      console.log(666, this.imgData2, file);
      for (let i = 0; i < this.imgData2.length; i++) {
        this.imgData2[i].uid == file.uid && this.imgData2.splice(i, 1);
      }
    },
    handlePictureCardPreview2(file) {
      this.dialogImageUrl2 = file.url;
      this.dialogVisible2 = true;
    }
  }
};
</script>
<style scoped>
.imgSpan {
  display: block;
  width: 145px;
  float: left;
  text-align: center;
  margin-right: 10px;
}
.primary {
  width: 100%;
  text-align: center;
  margin-top: 20px;
}
.f12 {
  font-size: 12px;
  color: #999;
  margin-top: 10px;
}
.img {
  width: 100px;
  border: 1px solid red;
  display: block;
  position: relative;
  top: 0;
  z-index: 999;
}
.shopList {
  width: 100%;
  /* border-bottom: 1px solid #ccc; */
  line-height: 50px;
  font-size: 16px;
  /* height: 30px; */
  /* margin-bottom: 30px; */
}
</style>
